package com.xujc.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.xujc.dao.imp.UserDAO;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.CookiesAware;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by xujc on 6/21/15.
 */
public class LoginInterceptor extends AbstractInterceptor implements CookiesAware{
    private Map<String, String> mMap;
    private UserDAO mUserDAO;

    @Override
    public String intercept(ActionInvocation actionInvocation) throws Exception {
        HttpServletRequest request = ServletActionContext.getRequest();
        Cookie[] cookies = request.getCookies();
        Cookie c=null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("uid")) {
                c=cookie;
                break;
            }
        }
        if (c == null) {
            request.setAttribute("logined", false);
            return actionInvocation.invoke();
        }
        String uid = c.getValue();
        if (uid!=null) {
            request.setAttribute("logined", true);
            request.setAttribute("userEnti",mUserDAO.getById(Integer.parseInt(uid)));
        } else {
            request.setAttribute("logined", false);
        }
        return actionInvocation.invoke();
    }

    @Override
    public void setCookiesMap(Map<String, String> map) {
        mMap = map;
    }

    public void setUserDAO(UserDAO userDAO) {
        mUserDAO = userDAO;
    }
}
